﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Reporting.WebForms;
using System.Configuration;
using System.Drawing.Printing;
using System.Collections;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Text;
using System.Drawing.Imaging;

namespace VisualWebGuiApplication2
{
    public partial class report3 : System.Web.UI.Page
    {
        int tankid = 0;
        private int m_currentPageIndex;
        private IList<Stream> m_streams;


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (null != Request.QueryString["id"])
                {
                    tankid = Convert.ToInt32(Request.QueryString["id"].ToString());
                    renderrep(tankid);
                }
            }
        }
        private void Export(LocalReport report,string filename)
        {
            



            string reportType = "pdf";
            string mimeType = "application/pdf";
            string encoding;
            string fileNameExtension;

            //The DeviceInfo settings should be changed based on the reportType
            //http://msdn2.microsoft.com/en-us/library/ms155397.aspx
            string deviceInfo =
            "<DeviceInfo>" +
            " <OutputFormat>PDF</OutputFormat>" +
            " <PageWidth>20cm</PageWidth>" +
            " <PageHeight>29.7cm</PageHeight>" +
            " <MarginTop>0.5cm</MarginTop>" +
            " <MarginLeft>0.5cm</MarginLeft>" +
            " <MarginRight>0.5cm</MarginRight>" +
            " <MarginBottom>0.5cm</MarginBottom>" +
            "</DeviceInfo>";

            Warning[] warnings;
            string[] streams;
            byte[] renderedBytes;

            //Render the report
            renderedBytes = reportViewer1.LocalReport.Render(
            reportType,
           deviceInfo,
           out mimeType,
           out encoding,
           out fileNameExtension,
           out streams,
           out warnings);

           
            //string filename = ConfigurationManager.AppSettings["invoicesfilepath"] + Guid.NewGuid().ToString();
          

            FileStream fs = new FileStream(filename + ".pdf", FileMode.Create);
            fs.Write(renderedBytes, 0, renderedBytes.Length);
            fs.Close();














        }
        // Routine to provide to the report renderer, in order to
        //    save an image for each page of the report.
        private Stream CreateStream(string name,
          string fileNameExtension, Encoding encoding,
          string mimeType, bool willSeek)
        {
            string filename = ConfigurationManager.AppSettings["invoicesfilepath"];
            Stream stream = new FileStream(filename + name +
               "." + fileNameExtension, FileMode.Create);
            m_streams.Add(stream);
            return stream;
        }
        // Handler for PrintPageEvents
        private void PrintPage(object sender, PrintPageEventArgs ev)
        {
            Metafile pageImage = new
               Metafile(m_streams[m_currentPageIndex]);
            ev.Graphics.DrawImage(pageImage, ev.PageBounds);
            m_currentPageIndex++;
            ev.HasMorePages = (m_currentPageIndex < m_streams.Count);
        }

        private void Print()
        {
            
        }

        public void renderrep(int invoiceid)
        {
            using (GazOnDevEntities db =new GazOnDevEntities())
            {
                string invoiceid_ = invoiceid.ToString();
              
                var query1 = from i in db.Invoices
                             where i.invoiceNumber == invoiceid_
                             select i;
               Invoice dd = query1.FirstOrDefault();

                var query2 = from i in db.invoiceitems
                             where i.invoiceid == invoiceid_
                             select i;
                List<invoiceitem> ds2 = query2.ToList<invoiceitem>();
                
              //  dd.FirstOrDefault().Datetime = Convert.ToDateTime(dd.FirstOrDefault().Datetime.Value.ToString("MM/dd/yyyy"));
                //dd.FirstOrDefault().Date_of_Fix = Convert.ToDateTime(dd.FirstOrDefault().Date_of_Fix.Value.ToString("MM/dd/yyyy"));
               
              //  int personSigned = Convert.ToInt32(query1.FirstOrDefault().PersonRecipetsignid);
                // int transportCompanyid = Convert.ToInt32(query1.FirstOrDefault().TransportCompanyID);
                 this.reportViewer1.LocalReport.DataSources.Clear();
                // this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", dd));
                 this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", ds2));
              //     SignPerson personrecipet=   db.SignPersons.FirstOrDefault(x=>x.id == personSigned);
                //  TransportCompany companytrans=   db.TransportCompanies.FirstOrDefault(x=>x.id == transportCompanyid);
                // ReportDataSource rds = new ReportDataSource("DataSet1", dd);
               //  this.reportViewer1.LocalReport.DataSources = dd;
                 DateTime temdate = Convert.ToDateTime(dd.date);
                 string DatetimeFormat = ConfigurationManager.AppSettings["DatetimeFormat"];
                 ReportParameter p1 = new ReportParameter("invoiceid", dd.invoiceNumber);
                 ReportParameter p2 = new ReportParameter("Datetime", temdate.ToString(DatetimeFormat));
                 ReportParameter p3 = new ReportParameter("transporter", dd.transporter);
                ReportParameter p4 = new ReportParameter("carnum", dd.carnum);
                ReportParameter p5 = new ReportParameter("address", dd.address);
                ReportParameter p6 = new ReportParameter("to", dd.C_to);
                 ReportParameter p7 = new ReportParameter("tankDesc", dd.tankDesc);
                 ReportParameter p8 = new ReportParameter("InvoiceType","מקור");
                 ReportParameter p9 = new ReportParameter("descrip", "צובר :");
             
                reportViewer1.LocalReport.SetParameters(new ReportParameter[] { p1, p2, p3,p4,p5,p6,p7 ,p8 ,p9});
          
                this.reportViewer1.DataBind();
                reportViewer1.LocalReport.Refresh();
               // string filename = ConfigurationManager.AppSettings["invoicesfilepath"] + Guid.NewGuid().ToString();
               // Export(reportViewer1.LocalReport, filename);
               // m_currentPageIndex = 0;
               // //Print();
               // string [] lisfilename=new  string[2]{filename+".pdf",filename+"copy.pdf"};
               //  p8 = new ReportParameter("InvoiceType", "העתק");

                
               // reportViewer1.LocalReport.SetParameters(new ReportParameter[] { p1, p2, p3, p4, p5, p6, p7, p8 });
               // this.reportViewer1.DataBind();
               // reportViewer1.LocalReport.Refresh();
               // Export(reportViewer1.LocalReport, filename+"copy");
               // CombineMultiplePDFs(lisfilename, filename + "combined.pdf");


               // //Open exsisting pdf
               // Document document = new Document(PageSize.LETTER);
               // PdfReader reader = new PdfReader(filename + "combined.pdf");
               // //Getting a instance of new pdf wrtiter
               // PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(
               //    filename + "Print.pdf", FileMode.Create));
               // document.Open();
               // PdfContentByte cb = writer.DirectContent;

               // int ii = 0;
               // int p = 0;
               // int n = reader.NumberOfPages;
               // Rectangle psize = reader.GetPageSize(1);

               // float width = psize.Width;
               // float height = psize.Height;

               // //Add Page to new document
               // while (ii < n)
               // {
               //     document.NewPage();
               //     p++;
               //     ii++;

               //     PdfImportedPage page1 = writer.GetImportedPage(reader, ii);
               //     cb.AddTemplate(page1, 0, 0);
               // }

               // //Attach javascript to the document
               // PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer);
               // writer.AddJavaScript(jAction);
               // document.Close();

               // frmPrint.Attributes["src"] = filename + "Print.pdf";
               // Response.Clear();
               // Response.ContentType = "application/pdf";
               //// Response.AddHeader("content-disposition", "attachment; filename="+filename + "Print.pdf");
               //// Stream fs = new FileStream(filename + "Print.pdf", FileMode.Open);
               // //combined


               // byte[] renderedBytes = GetBytesFromFile(filename + "Print.pdf");
               //Response.BinaryWrite(renderedBytes);
               // Response.End();
            }

           

        }

        public static byte[] GetBytesFromFile(string fullFilePath)
        {
            // this method is limited to 2^32 byte files (4.2 GB)

            FileStream fs = File.OpenRead(fullFilePath);
            try
            {
                byte[] bytes = new byte[fs.Length];
                fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
                fs.Close();
                return bytes;
            }
            finally
            {
                fs.Close();
            }

        }

        public static void CombineMultiplePDFs(string[] fileNames, string outFile)
        {
            int pageOffset = 0;
            ArrayList master = new ArrayList();
            int f = 0;
            Document document = null;
            PdfCopy writer = null;
            while (f < fileNames.Length)
            {
                // we create a reader for a certain document
                PdfReader reader = new PdfReader(fileNames[f]);
                reader.ConsolidateNamedDestinations();
                // we retrieve the total number of pages
                int n = reader.NumberOfPages;
                pageOffset += n;
                if (f == 0)
                {
                    // step 1: creation of a document-object
                    document = new Document(reader.GetPageSizeWithRotation(1));
                    // step 2: we create a writer that listens to the document
                    writer = new PdfCopy(document, new FileStream(outFile, FileMode.Create));
                    // step 3: we open the document
                    document.Open();
                }
                // step 4: we add content
                for (int i = 0; i < n; )
                {
                    ++i;
                    if (writer != null)
                    {
                        PdfImportedPage page = writer.GetImportedPage(reader, i);
                        writer.AddPage(page);
                    }
                }
                PRAcroForm form = reader.AcroForm;
                if (form != null && writer != null)
                {
                    writer.CopyAcroForm(reader);
                }
                f++;
            }
            // step 5: we close the document
            if (document != null)
            {
                document.Close();
            }
        }
        //private void Print()
        //{

        //    Warning[] warnings;
        //    string[] streamids;
        //    string mimeType;
        //    string encoding;
        //    string extension;
        //    string  filename = ConfigurationManager.AppSettings["invoicesfilepath"]+ Guid.NewGuid().ToString();
        //    byte[] bytes = reportViewer1.LocalReport.Render("PDF", null, out mimeType,
        //                   out encoding, out extension, out streamids, out warnings);

        //    FileStream fs = new FileStream(filename+".pdf", FileMode.Create);
        //    fs.Write(bytes, 0, bytes.Length);
        //    fs.Close();

        //    //Open exsisting pdf
        //    Document document = new Document(PageSize.LETTER);
        //    PdfReader reader = new PdfReader(filename + ".pdf");
        //    //Getting a instance of new pdf wrtiter
        //    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(
        //       filename + "Print.pdf", FileMode.Create));
        //    document.Open();
        //    PdfContentByte cb = writer.DirectContent;

        //    int i = 0;
        //    int p = 0;
        //    int n = reader.NumberOfPages;
        //    Rectangle psize = reader.GetPageSize(1);

        //    float width = psize.Width;
        //    float height = psize.Height;

        //    //Add Page to new document
        //    while (i < n)
        //    {
        //        document.NewPage();
        //        p++;
        //        i++;

        //        PdfImportedPage page1 = writer.GetImportedPage(reader, i);
        //        cb.AddTemplate(page1, 0, 0);
        //    }

        //    //Attach javascript to the document
        //    PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer);
        //    writer.AddJavaScript(jAction);
        //    document.Close();

        //    //Attach pdf to the iframe
        //    frmPrint.Attributes["src"] = filename+"Print.pdf";
        //}
    }
}